# -*- coding:utf-8 -*-
"""Created By Corvo"""

from base import LogicBlockServerBase
from .....common.system import *
from ...const import ModuleEvent


class LogicRpcDoubleBlockServer(LogicBlockServerBase):
    """逻辑双端方块服务端"""
    __mVersion__ = 1

    def __init__(self, name, dim, pos):
        super(LogicRpcDoubleBlockServer, self).__init__(name, dim, pos)
        self.rpc_key = Misc.CreateUUID()
        self.rpc = self.ModuleSystem.CreateRpcModule(self, self.rpc_key)
        self.dirty_player = set()
        # 同步玩家 完成界面创建
        self.syn_player = set()

    def OnDestroy(self):
        self.rpc.Discard()
        del self.rpc
        super(LogicRpcDoubleBlockServer, self).OnDestroy()

    # -----------------------------------------------------------------------------------

    def client(self, target=None):
        return self.rpc(target)

    # -----------------------------------------------------------------------------------

    def AddPlayer(self, player_id):
        if not self.IsFinishedLoad():
            self.dirty_player.add(player_id)
            return
        super(LogicRpcDoubleBlockServer, self).AddPlayer(player_id)
        self.NotifyToClient(player_id, ModuleEvent.ModuleOnBlockAddPlayerEvent, {
            "id": self.id,
            "rpc": self.rpc_key,
            "data": self.GetBlockSynData()
        })

    def DelPlayer(self, player_id):
        self.syn_player.discard(player_id)
        super(LogicRpcDoubleBlockServer, self).DelPlayer(player_id)

    # -----------------------------------------------------------------------------------

    def OnFinishedLoadData(self):
        super(LogicRpcDoubleBlockServer, self).OnFinishedLoadData()
        for player_id in list(self.dirty_player):
            self.AddPlayer(player_id)
        self.dirty_player.clear()

    # 玩家完成界面创建
    def OnPlayerFinishedCreateUI(self, player_id):
        # type: (str) -> None
        """玩家完成界面创建"""
        self.syn_player.add(player_id)

    # 获取方块同步数据
    def GetBlockSynData(self):
        return self.storage
